﻿using System;
using System.Configuration;
using System.IO;
using NDBGen.Configuration;
using NDBGen.Plugins;

namespace NDBGen
{
    internal static class ProjectManagement
    {
        public static FileInfo LoadProjectFile(ProjectManagedEntryConfigurationElement config, PluginLibraries libraries, out IProjectFileManager projectFileManager, out Boolean hasProject, out String outputRootPath)
        {
            projectFileManager = libraries.DataAccessProjectFileManagers.FindOne(m => m.ConfigurationName == config.ProjectFileManager);
            if (config.ProjectFileManager != null && projectFileManager == null) throw new ConfigurationErrorsException(String.Format("Could not find a project manager implementation named '{0}'.", config.ProjectFileManager));

            hasProject = projectFileManager != null;
            FileInfo projectFile = null;

            if (hasProject)
            {
                projectFile = Parser.FindSourceFile(config.ProjectFile);
                projectFileManager.Load(projectFile.FullName);
                outputRootPath = projectFile.DirectoryName;
            }

            if (!String.IsNullOrEmpty(config.ProjectRoot))
            {
                if (!Directory.Exists(config.ProjectRoot)) throw new DirectoryNotFoundException(String.Format("The directory configured for the project root ({0}) does not exist.", config.ProjectRoot));
                outputRootPath = config.ProjectRoot;
            }
            else if (projectFile != null) outputRootPath = projectFile.Directory.FullName;            
            else throw new ConfigurationErrorsException(String.Format("Either projectFile or projectRoot must be configured.{0}Project File Manager: {1}{0}Project File: {2}{0}Project Root: {3}",
                Environment.NewLine,
                config.ProjectFileManager ?? "(null)",
                config.ProjectFile ?? "(null)",
                config.ProjectRoot ?? "(null)"));

            return projectFile;
        }

        public static FileInfo GetOutputFile(String outputRootPath, String rootPath)
        {
            var file = new FileInfo(Path.Combine(outputRootPath, rootPath));
            var dir = file.Directory;
            if (!dir.Exists) dir.Create();

            return file;
        }
    }
}
